# coding: utf-8
from PySide6.QtCore import Qt
from PySide6.QtGui import QImage, QColor
from PySide6.QtWidgets import QVBoxLayout, QWidget, QHBoxLayout
from qfluentwidgets import BodyLabel, setFont, IconWidget, FluentIcon, PushButton, PrimaryPushButton

from .base import TopBaseInterface, ChapterWidget
from ...common import signalBus, BookInfoModel, BookItemModel, APIBase
from ...components import ImageLabel, queue_thread_manager


class TagWidget(QWidget):
    def __init__(self, icon, text: str, parent=None):
        super().__init__(parent)
        self.horizontalLayout = QHBoxLayout(self)
        self.iconWidget = IconWidget(icon, self)
        self.label = BodyLabel(text, self)

        self.iconWidget.setFixedSize(16, 16)
        self.horizontalLayout.setContentsMargins(0, 0, 0, 0)
        self.horizontalLayout.setAlignment(Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter)
        self.horizontalLayout.addWidget(self.iconWidget)
        self.horizontalLayout.addWidget(self.label)

        self.label.setTextColor(QColor(0, 0, 0, 100), QColor(255, 255, 255, 100))

    def setIcon(self, icon):
        self.iconWidget.setIcon(icon)

    def setText(self, text):
        self.label.setText(text)
        self.label.adjustSize()

    def clear(self):
        self.label.clear()


class InfoWidget(QWidget):

    def __init__(self, parent=None):
        super().__init__(parent)
        self.horizontalLayout = QHBoxLayout(self)
        self.verticalLayout = QVBoxLayout()
        self.horizontalLayout_2 = QHBoxLayout()
        self.coverLabel = ImageLabel(self)
        self.titleLabel = BodyLabel('漫画名称', self)
        self.authorLabel = BodyLabel('作者', self)
        self.tagWidget = TagWidget(FluentIcon.TAG, '标签', self)
        self.latestChapterLabel = TagWidget(FluentIcon.GLOBE, '最新章节', self)
        self.updateTimeLabel = TagWidget(FluentIcon.CALENDAR, '更新时间', self)
        self.descriptionLabel = BodyLabel('简介', self)
        self.addButton = PrimaryPushButton(FluentIcon.BOOK_SHELF, '添加到书架', self)

        self.__initWidgets()

    def __initWidgets(self):
        self.setFixedHeight(400)
        self.coverLabel.setScaledContents(True)
        self.coverLabel.setFixedSize(240, 320)
        self.coverLabel.setRadius(5)
        setFont(self.titleLabel, 22)
        self.descriptionLabel.setWordWrap(True)
        self.descriptionLabel.setTextColor(QColor(0, 0, 0, 150), QColor(245, 245, 245, 150))
        self.descriptionLabel.setTextFormat(Qt.TextFormat.RichText)

        self.horizontalLayout.setContentsMargins(40, 40, 40, 40)
        self.horizontalLayout.addWidget(self.coverLabel)
        self.horizontalLayout.addSpacing(20)
        self.verticalLayout.setAlignment(Qt.AlignmentFlag.AlignVCenter)
        self.verticalLayout.addWidget(self.titleLabel)
        self.verticalLayout.addWidget(self.authorLabel)
        self.verticalLayout.addWidget(self.tagWidget)
        self.verticalLayout.addWidget(self.latestChapterLabel)
        self.verticalLayout.addWidget(self.updateTimeLabel)
        self.verticalLayout.addWidget(self.descriptionLabel)

        self.horizontalLayout_2.setContentsMargins(0, 0, 0, 0)
        self.horizontalLayout_2.setAlignment(Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter)
        self.horizontalLayout_2.addWidget(self.addButton)
        self.verticalLayout.addLayout(self.horizontalLayout_2)

        self.horizontalLayout.addLayout(self.verticalLayout)

    def setModel(self, model: BookInfoModel):
        self.titleLabel.setText(model.title)
        author_list = model.author.strip().split(',')
        author = []
        for aut in author_list:
            aut = aut.strip()
            if aut:
                author.append(aut)
        self.authorLabel.setText(','.join(author))
        tags = []
        for tag in model.tags:
            tag = tag.strip()
            if tag:
                tags.append(tag)
        self.tagWidget.setText('  '.join(tags))
        self.latestChapterLabel.setText(f'最新章节：{model.latestChapterName}')
        self.updateTimeLabel.setText(f'更新时间：{model.lastUpdate}')
        self.descriptionLabel.setText(model.desc)

        self.coverLabel.setUrl(model.cover, model.source.headers)

    def clear(self):
        self.titleLabel.clear()
        self.authorLabel.clear()
        self.tagWidget.clear()
        self.latestChapterLabel.clear()
        self.updateTimeLabel.clear()
        self.descriptionLabel.clear()
        self.coverLabel.clear()


class InfoInterface(TopBaseInterface):

    def __init__(self, parent=None):
        super().__init__(parent)
        self.view = QWidget()
        self.verticalLayout = QVBoxLayout(self.view)
        self.infoWidget = InfoWidget(self)
        self.chapterWidget = ChapterWidget(self)

        self.setObjectName('InfoInterface')
        self.setWidget(self.view)

        self.setViewportMargins(0, 40, 0, 0)

        self.verticalLayout.setContentsMargins(0, 0, 0, 0)
        self.verticalLayout.setAlignment(Qt.AlignmentFlag.AlignTop)
        self.verticalLayout.addWidget(self.infoWidget)
        self.verticalLayout.addWidget(self.chapterWidget)
        self.view.setLayout(self.verticalLayout)

        self.closed.connect(self.clear)
        self.infoWidget.addButton.clicked.connect(self.addBook)

    def loadInfo(self, obj: APIBase, url: str):
        # info_url = 'https://cn.baozimhcn.com/comic/xieelianjinzhushigaobudingzijideshiyanti-yunhaijinggewenhuazuozhelimodao'
        queue_thread_manager.send_function(obj.info, url, slot=self.onResult)

    def onResult(self, result: BookInfoModel):
        self.infoWidget.setModel(result)
        self.chapterWidget.setProperty('useBrowser', result.useBrowser)
        self.chapterWidget.setModel(result.chapters)
        self.setProperty('bookInfo', result)

    def clear(self):
        self.infoWidget.clear()
        self.chapterWidget.clear()
        self.verticalScrollBar().setValue(0)

    def addBook(self):
        book_info: BookInfoModel = self.property('bookInfo')
        if not book_info:
            return
        signalBus.addBookSignal.emit(BookItemModel(
            title=book_info.title,
            desc=book_info.desc,
            cover=book_info.cover,
            tags=','.join(book_info.tags),
            info_url=book_info.url,
            source=book_info.source
        ))
